package com.fc.advbox.shiro.common;

import com.fc.advbox.entity.SessionEntity;
import com.fc.advbox.service.ISessionService;
import org.apache.shiro.io.DefaultSerializer;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.ValidatingSession;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.Date;

public class AdvSessionDao extends EnterpriseCacheSessionDAO {

    @Autowired
    private ISessionService sessionService;

    private DefaultSerializer<AdvSession> serializer = new DefaultSerializer<AdvSession>();

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.doCreate(session);

        if (isAppSession(session)) {
            AdvSession advSession = (AdvSession) session;
            SessionEntity sessionEntity = new SessionEntity();
            sessionEntity.setSessionId(sessionId.toString());
            sessionEntity.setSession(serializer.serialize(advSession));
            sessionService.save(sessionEntity);
        }
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        SessionEntity entity = sessionService.getSession(sessionId.toString());
        if(entity != null){
            AdvSession advSession = serializer.deserialize(entity.getSession());
            advSession.setLastAccessTime(new Date());
            return advSession;
        }
        return null;
    }

    @Override
    protected void doUpdate(Session session) {
        super.doUpdate(session);
        if (session instanceof ValidatingSession && !((ValidatingSession) session).isValid()) {
            return; //如果会话过期/停止 没必要再更新了
        }
        SessionEntity entity = sessionService.getSession(session.getId().toString());
        if (entity != null) {
            entity.setSession(serializer.serialize((AdvSession) session));
            sessionService.update(entity);
        }
    }

    @Override
    protected void doDelete(Session session) {
        super.doDelete(session);
    }

    private boolean isAppSession(Session session) {
        AdvSession advSession = (AdvSession) session;
        return (advSession.getPlatform() == AdvSession.Platform.ios
                || advSession.getPlatform() == AdvSession.Platform.android
                || advSession.getPlatform() == AdvSession.Platform.wp);
    }
}
